package com.googlecode.carlosmonterocanabal.mojosprites;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import javax.imageio.ImageIO;


import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

import com.googlecode.carlosmonterocanabal.mojosprites.sprites.ImagePacker;


/**
 * Genera una imagen con el sprite a partir de todas las imagenes indicadas.
 * 
 * @goal spride
 * 
 * @phase compile
 * 
 */
public class GenerateSprites extends AbstractMojo {

    /**
     * Location of the file.
     * 
     * @parameter expression="${project.build.directory}"
     * @required
     */
    private File outputDirectory;

    /**
     * Directories to generate sprite
     * 
     * @parameter
     * @required
     */
    private List directories;

    /**
     * Directories to generate sprite
     * 
     * @parameter
     */
    private List directoriesToDelete;

    /**
     * Extensions of image files
     * 
     * @parameter
     * @required
     */
    private List extensions;

    /**
     * Extensions of image files
     * 
     * @parameter
     */
    private String directoryToSprite;

    /**
     * Extensions of image files
     * 
     * @parameter default-value="sprite.png"
     */
    private String nameSprite;

    /**
     * Extensions of image files
     * 
     * @parameter default-value="spriteIndexes.properties"
     */
    private String nameIndexes;

    public void execute() throws MojoExecutionException {

        ImagePacker imagePacker = new ImagePacker();

        List<Entry<String, String>> fileNames = new ArrayList<Entry<String, String>>();

        for (String directory : (List<String>) directories) {

            File imageFolder = new File(outputDirectory.getAbsolutePath() + "/classes" + directory);

            try {
                for (File file : FileUtils.getFileListing(imageFolder)) {
                    if (file.isFile()) {
                        for (String fileType : (List<String>) extensions) {
                            if (file.getAbsolutePath().endsWith(fileType)) {
                                fileNames.add(new SimpleEntry<String, String>(
                                        file.getAbsolutePath().split("classes")[1].replace("\\", "/"), file
                                                .getAbsolutePath()));
                                break;
                            }
                        }
                    }
                }
            } catch (FileNotFoundException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }

        }

        Entry<BufferedImage, Map<String, Rectangle>> result = imagePacker.packImage(fileNames, 5000, 5000, 1, getLog());

        try {
            getLog().info("Saving spride...");
            ImageIO.write(result.getKey(), "png", new File(outputDirectory.getAbsolutePath()
                    + (directoryToSprite == null ? "" : directoryToSprite), nameSprite));
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }

        try {
            Properties props = new Properties();
            for (Entry<String, Rectangle> entry : result.getValue().entrySet()) {
                Rectangle r = entry.getValue();
                props.put(entry.getKey(), r.x + "," + r.y + "," + r.width + "," + r.height);
            }
            getLog().info("Saving indexes...");
            props.store(new FileOutputStream(new File(outputDirectory.getAbsolutePath() + "/classes", nameIndexes)),
                    "Fichero de posiciones para el sprite");

        } catch (Exception e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }

        for (String directory : directoriesToDelete == null ? (List<String>) directories
                : (List<String>) directoriesToDelete) {

            if (!FileUtils.removeDirectory(new File(outputDirectory.getAbsolutePath() + "/classes" + directory))) {
                throw new MojoExecutionException("Error al eliminar el directorio: " + directory);
            }

        }

    }

}
